/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode* head) {
    struct ListNode* slow, * fast;
    slow = fast = head;

    while (fast && fast->next)
    {
        fast = fast->next->next;
        slow = slow->next;
        if (fast == slow)
            return true;
    }
    return false;
}
struct ListNode* detectCycle(struct ListNode* head) {
    struct ListNode* fast, * slow;
    slow = fast = head;
    if (hasCycle(head))
    {
        do {
            slow = slow->next;
            fast = fast->next->next;
        } while (slow != fast);
        struct ListNode* meet = slow;
        while (meet != head)
        {
            meet = meet->next;
            head = head->next;
        }
        return meet;
    }
    else
        return NULL;

}